package cn.kmia.hrm.action.system;

import cn.kmia.hrm.pojo.system.User;
import cn.kmia.hrm.service.system.UserService;
import com.kmia.ssoFilter.SSOFilter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.integration.shiro.SimpleShiroToken;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: hrm
 * @description: 用户操作类
 * @author: 4K
 * @create: 2018-04-16 14:35
 **/
@IocBean
@At("/user")
public class UserAction {

    private static final Log log = Logs.get();

    @Inject
    protected UserService userService;

    @Inject
    protected PropertiesProxy conf;

    /**
     * 登陆
     */
    @GET
    @At("/toLogin")
    public void loginFromSSO(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取用户session
        User user = (User) request.getSession().getAttribute("user");
        // 获取cookies
        Cookie[] cookies = request.getCookies();
        // 用户员工编号
        String userIdCard;
        // 判断用户session是否有效
        if (user != null) {
            if (cookies != null) {
                // 判断token是否存在，并且有效
                userIdCard = SSOFilter.validateToken(request);
                if (userIdCard != null && !"".equals(userIdCard)) {
                    // token存在，并且有效,跳转首页
                    response.sendRedirect(conf.get("indexUrl"));
                    return; // 不加会报错 Cannot call sendRedirect() after the response has been committed
                }
            }
        } else {
            if (cookies != null) {
                // 判断token是否存在，并且有效
                userIdCard = SSOFilter.validateToken(request);
                if (userIdCard != null && !"".equals(userIdCard)) {
                    // token存在，并且有效，获取用户信息，生成新session
                    user = userService.getUser(userIdCard);
                    request.getSession().setAttribute("user", user);
                    SecurityUtils.getSubject().login(new SimpleShiroToken(user.getId()));
                    response.sendRedirect(conf.get("indexUrl"));
                    return;
                }
            }
        }
        // sso生成的令牌
        String token = request.getParameter("token");
        // 令牌包含的登录信息（token和idCard）
        String[] loginInfo = null;
        if (token != null && !"".equals(token)) {
            loginInfo = token.split("_");
        }
        if (loginInfo != null) {
            user = userService.getUser(loginInfo[1]);
            if (user != null) {
                request.getSession().setAttribute("user", user);
                SecurityUtils.getSubject().login(new SimpleShiroToken(user.getId()));
                // 生成token的cookie
                Cookie tokenCookie = new Cookie(SSOFilter.cookieName,
                        loginInfo[0]);
                // 设置路径
                tokenCookie.setPath(request.getContextPath());
                // cookie有效期
                tokenCookie.setMaxAge(Integer.valueOf(conf.get("tokenInterval")));
                // 设置cookie
                response.addCookie(tokenCookie);
                response.sendRedirect(conf.get("indexUrl"));
                return;
            } else {
                log.info("用户：" + loginInfo[1] + "不存在！");
                response.sendRedirect(request.getContextPath()+"/error.html");
                return;
            }
        }
        // 获取不到登录信息，或者登录信息不正确，跳转SSO
        response.sendRedirect(SSOFilter.SSOLoginPage);
    }

    /**
     * 新增用户
     *
     * @param newUser 用户信息
     * @param user    操作者
     * @return
     */
    @At("/add")
    @Ok("json:full")
    @RequiresPermissions("user:add")
    public Object add(@Param("..") User newUser, @Attr(scope = Scope.SESSION, value = "user") User user) {
        NutMap nm = new NutMap();
        newUser = userService.add(newUser, user.getUser_idcard());
        if (newUser == null) {
            nm.setv("success", false).setv("errorMsg", "创建用户失败，请联系管理员");
        } else {
            nm.setv("success", true);
        }
        return nm;
    }

    /**
     * 更新
     *
     * @param updateUser
     * @param user
     * @return
     */
    @At("/update")
    @Ok("json:full")
    @RequiresPermissions("user:update")
    public Object update(@Param("..") User updateUser, @Attr(scope = Scope.SESSION, value = "user") User user) {
        NutMap re = new NutMap();
        try {
            if (userService.update(updateUser, user.getUser_idcard())) {
                re.setv("success", true);
            } else {
                re.setv("success", false);
            }
        } catch (Exception e) {
            re.setv("success", false);
            log.error("更新异常", e);
        }
        return re;
    }

    /**
     * 删除
     *
     * @param ids int[]
     * @return
     */
    @At("/del")
    @Ok("json:full")
    @RequiresPermissions("user:del")
    public Object del(@Param("ids") int[] ids) {
        NutMap re = new NutMap();
        try {
            if (ids != null) {
                re = userService.del(ids);
            } else {
                re.setv("success", false);
            }
        } catch (Exception e) {
            re.setv("success", false);
            log.error("删除异常", e);
        }
        return re;
    }

    /**
     * 分页显示全部用户
     *
     * @param pager 分页
     * @return
     */
    @At
    @Ok("json:full")
    @RequiresPermissions("user:queryByPage")
    public Object queryByPage(@Param("..") Pager pager, @Param("user_idcard") String user_idcard, @Param("user_name") String user_name) throws Exception {
        NutMap nm = new NutMap();
        QueryResult userList = userService.queryByPage(user_idcard, user_name, pager);
        nm.setv("rows", userList.getList());
        nm.setv("total", userList.getPager().getRecordCount());
        return nm;
    }

    /**
     * 注销
     *
     * @param request
     */
    @At
    @Ok(">>:/")
    public void logout(HttpServletRequest request,HttpServletResponse response) {
        request.getSession().invalidate();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie tmpCookie : cookies) {
                if ("rememberMe".equals(tmpCookie.getName()) || "token".equals(tmpCookie.getName())) {
                    Cookie cookie = new Cookie(tmpCookie.getName(), "");// 清空得用"",不能用null
                    cookie.setPath(request.getContextPath() + "/");// 设置保存路径
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
    }

    /**
     * 查询用户名是否存在
     *
     * @param user_idcard
     * @return false 存在 true 不存在
     */
    @At("/find")
    @Ok("json:full")
    public Object find(@Param("user_idcard") String user_idcard) {
        NutMap re = new NutMap();
        try {
            if (userService.isRepeat(user_idcard)) {
                re.setv("valid", false);
            } else {
                re.setv("valid", true);
            }
        } catch (Exception e) {
            re.setv("exist", false);
            log.error("查询用户名是否存在存在异常", e);
        }
        return re;
    }

    /**
     * 重置密码
     *
     * @param password
     * @param user
     * @return
     */
    @At("/resetPwd")
    @Ok("json:full")
    public Object add(@Param("password") String password, @Attr(scope = Scope.SESSION, value = "user") User user) {
        NutMap nm = new NutMap();
        if (!userService.resetPwd(password, user)) {
            nm.setv("success", false).setv("errorMsg", "重置密码失败，请联系管理员");
        } else {
            nm.setv("success", true);
        }
        return nm;
    }

    /**
     * 获取登录用户权限信息
     *
     * @param user
     * @return
     */
    @At("/getAuth")
    @Ok("json:full")
    public User getRolesAndPers(@Attr(scope = Scope.SESSION, value = "user") User user) {
        return userService.getRolesAndPers(user);
    }
}
